﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using UniMana.Utils.Configs;
namespace UniMana.Utils.Helper
{
    public static class CheckBeforDelete
    {
        public static bool Check(string _strTableName,string _strColumnName, object _objValue)
        {
            //Lấy danh sách các bảng
            DataTable tablesName = GetAllTablesName(_strColumnName);
            if (tablesName != null)
            {
                for (int i = 0; i < tablesName.Rows.Count; i++)
                {
                    if (tablesName.Rows[i]["TABLE_NAME"].ToString() != _strTableName)
                    {
                        if (!CheckOneTable(_strColumnName, tablesName.Rows[i]["TABLE_NAME"].ToString(), _objValue.ToString()))
                        {
                            return false;
                        }
                    }
                }
                return true;
            }
            else
            {
                return true;
            }
        }

        private static DataTable GetAllTablesName(string _strColumnName)
        {
            string sqlQuery = "SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME IN  (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE') AND COLUMN_NAME=N'" + _strColumnName + "';";
            SqlConnection sqlConnection = new SqlConnection(ServerConfig.m_strConnectionString);
            sqlConnection.Open();
            SqlDataAdapter da = new SqlDataAdapter(sqlQuery, sqlConnection);
            DataTable dt = new DataTable();
            da.Fill(dt);
            sqlConnection.Close();
            if (dt.Rows.Count > 0)
            {
                return dt;
            }
            else
            {
                return null;
            }
        }
        private static bool CheckOneTable(string _strColumnName, string _strTableName,string _strValue)
        {
            string sqlQuery = "SELECT " + _strColumnName + " FROM [" + _strTableName + "] WHERE " + _strColumnName + "='" + _strValue + "'";
            SqlConnection sqlConnection = new SqlConnection(ServerConfig.m_strConnectionString);
            sqlConnection.Open();
            SqlDataAdapter da = new SqlDataAdapter(sqlQuery, sqlConnection);
            DataTable dt = new DataTable();
            da.Fill(dt);
            sqlConnection.Close();
            if (dt.Rows.Count > 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }
}
